<?php
class Ajax_UserShippingController extends Model3_Controller
{
    private $dateInitRoute=null;
    private $order;
    public function init()
    {
        $this->view->setUseTemplate(false);
    }

    public function calculateShippingPerRouteAction()
    {
        set_time_limit(3600);
        $credentials = Model3_Auth::getCredentials();
        $em = $this->getEntityManager('DefaultDb');
        $scheduleAdapter = $em->getRepository('DefaultDb_Entities_Schedule');
        $routePointsAdapter = $em->getRepository('DefaultDb_Entities_RoutePoint');
        $user = $em->find('DefaultDb_Entities_User', $credentials['id']);
        $userRepos = $em->getRepository('DefaultDb_Entities_User');
        $response = new stdClass();
        $response->res = false;
        $response->factors=0;
        $response->message = 'No se ha podido calcular la hora de recolecci&oacuten';
        
       

        if($this->getRequest()->isPost() && $user instanceof DefaultDb_Entities_User)
        {
            $post = $this->getRequest()->getPost();
            $idSchedule = $post['idRoute'];//? es idschedule
            $orderId = isset($post['orderId']) ? $post['orderId'] : null;
            if($orderId)
            {
                $this->order = $em->getRepository('DefaultDb_Entities_M3CommerceOrder')->find($orderId);
                if($user->getId()!==$this->order->getSeller()->getId())
                {
                    $user = $this->order->getSeller(); //Cambiamos el usuario ya que el que hace el pedido es el comprador
                }
            }
            else
            {
                $this->order = null;
                $idUser = $post['idSeller'];
                $user = $userRepos->find($idUser);
            }
            
            $scheduleSelect = $scheduleAdapter->find($idSchedule);
            $scheduleHelper = new Helper_Schedule($em);
            
            if($scheduleSelect instanceof  DefaultDb_Entities_Schedule)
            {
                $route = $scheduleSelect->getRoute();
                /** 
                 * Buscamos el punto del vendedor, apartir del branches_user
                 */
                $point = $em->find('DefaultDb_Entities_BranchesUser', $post['pointSeller']);
                $point = $point->getPoint();
                /**
                 * Buscamos la relacion entre el punto del comprador y la ruta.
                 */
                $MyRoutePoint = $routePointsAdapter->findOneBy(array('route'=>$route,'point'=>$point)); // deberia tener relacion el nombre con el seller 
                if($MyRoutePoint instanceof DefaultDb_Entities_RoutePoint )
                {
                    $shippingDate = $scheduleHelper->getNextDatesInRecurrent($scheduleSelect);
                    $this->dateInitRoute = new DateTime($shippingDate->format('Y-m-d H:i:s'));
                    $newShippingDate = new DateTime($shippingDate->format('Y-m-d H:i:s'));                    
                    $scheduleHelper->setOrder($this->order);
                    $scheduleHelper->setDateInitRoute($this->dateInitRoute);
                    $shippingDate = $scheduleHelper->calculateRecolection($shippingDate,$route,$MyRoutePoint);
//                     $shippingDate = $this->calculateRecolection($shippingDate,$route,$MyRoutePoint);

                    $response->res = true;
                    $response->message = 'La fecha estimada de recolecci&oacute;n en su domicilio es: '.$shippingDate->format('Y-m-d H:i:s');
                    $response->date = $shippingDate->format('Y-m-d H:i:s');
                    
                    /*BUYER*/
                    //buscar la ruta y si existe la eliminamos :D
                    $entities=$em->getRepository('DefaultDb_Entities_SequentialActivities')->findBy(array('order'=>$this->order));
                    foreach ($entities as $entity)
                        $em->remove($entity);
                    $em->flush();
                    
                    //Calculo de tiempos para el comprador
                    $idBuyer = (isset($post['buyerId'])? $post['buyerId']: $credentials['id']);
                    $buyer = $em->find('DefaultDb_Entities_User', $idBuyer);
                    /**
                     * Obtenemos el branch user del comprador
                     */
                    $branches= $em->find('DefaultDb_Entities_BranchesUser',$post['pointBuyer']);
                    $buyerPoint = $branches->getPoint();
                    
                    /**
                     * Agregamos el punto de recoleccion
                     */
                    $scheduleHelper->addPointRoute($response->date,'Recolección ',$MyRoutePoint->getPoint()->getName()); //Punto inicial
                    
                    $sequentialActivities = new DefaultDb_Entities_SequentialActivities;
                    $sequentialActivities->setRoutePoint($MyRoutePoint);
                    $sequentialActivities->setShippingDate($shippingDate);
                    $sequentialActivities->setType(DefaultDb_Entities_SequentialActivities::TYPE_RECOLECTION);
                    $sequentialActivities->setOrder($this->order);
                    $sequentialActivities->setRouteDate($this->dateInitRoute);
                    $em->persist($sequentialActivities);
                    
                    $routePointBuyer = $routePointsAdapter->findOneBy(array('point'=>$buyerPoint));
                    $routeBuyer = $routePointBuyer->getRoute();
                    
                    $routeBuyerId = $routePointsAdapter->getRouteByPointAndRoute($buyerPoint, $route);
                    
                    
                    $shippingDateDelivery = $scheduleHelper->calculateDelivery($buyer,$newShippingDate,$route, $routeBuyerId, $MyRoutePoint, $routePointBuyer);
                    $this->dateInitRoute = $scheduleHelper->getDateInitRoute();
                    if( !$shippingDateDelivery )
                    {
                        $response->message .= '<br/>No se ha podido calcular la hora de entrega';
                        $response->res = false;
                    }
                    else
                    {//BUYER
                        
                        $response->message .= '<br/> La fecha estimada de entrega es: '.$shippingDateDelivery->format('Y-m-d H:i:s');
                        $response->dateDelivery = $shippingDateDelivery->format('Y-m-d H:i:s');
                        $response->message .= '<br/><br/>Puntos Intermedios:';
                        //$this->pointsRoute[] = '['.$shippingDateDelivery->format('Y-m-d H:i:s').'] '. $buyerPoint->getName(); //Punto final
                        $scheduleHelper->addPointRoute($shippingDateDelivery->format('Y-m-d H:i:s'),'Entrega ', $buyerPoint->getName()); //Punto inicial
                        $pointsRoutesH = $scheduleHelper->getPointsRoute();
                        
                        foreach($pointsRoutesH as $pointRoute)
                        { 
                            $response->message .= '<br/>['. $pointRoute['start_date'].'] '.$pointRoute['type'].$pointRoute['name'];
                        }
                        $response->factors=$scheduleHelper->getRoutesFactor();//$this->routesFactor;
                        $sequentialActivitiesDelivery = new DefaultDb_Entities_SequentialActivities;
                        $sequentialActivitiesDelivery->setRoutePoint($routePointBuyer);
                        $sequentialActivitiesDelivery->setShippingDate($shippingDateDelivery);
                        $sequentialActivitiesDelivery->setType(DefaultDb_Entities_SequentialActivities::TYPE_DELIVERY);
                        $sequentialActivitiesDelivery->setOrder($this->order);
                        $sequentialActivitiesDelivery->setRouteDate($this->dateInitRoute);
                        $em->persist($sequentialActivitiesDelivery);
                        $em->flush();
                    }
                }
            }
        }
        $this->view->response = json_encode($response);
    }
    
    public function getSchedulesByOriginAction()
    {
        $em =  $this->getEntityManager('DefaultDb');
        $scheduleAdapter =  $em->getRepository('DefaultDb_Entities_Schedule');
        if($this->getRequest()->isPost())
        {
            $post = $this->getRequest()->getPost();
            if(isset($post['originPoint']))
            {
                $branchUser = $em->find('DefaultDb_Entities_BranchesUser', $post['originPoint']);
                if($branchUser)
                {
                    if($branchUser->getPoint())
                    {
                        $arrayDates = $scheduleAdapter->getNextSchedulesByRouteAndPointBranch($branchUser->getClient()->getId(),$branchUser->getPoint()->getId(),20,true);
                        $helper = new Helper_Schedule($em);
                        $this->view->schedules = $helper->getNextDatesValid($arrayDates);
                    }
                }
            }
        }
    }
}
?>
